<template>
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input placeholder="请你输入搜索用户名" v-model="keyword"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          @click="search"
          :disabled="keyword ? false : true"
        >
          搜索
        </el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser">
      添加用户
    </el-button>
    <el-button
      type="primary"
      size="default"
      @click="deleteSelectUser"
      :disabled="selectIdArr.length ? false : true"
    >
      批量删除
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      style="margin: 10px 0px"
      border
      :data="userArr"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.username}?`"
            width="260px"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasUser"
      @size-change="handler"
    />
  </el-card>
  <!-- 抽屉--添加用户/更新已有的用户信息 -->
  <el-drawer v-model="drawer" :direction="direction">
    <template #header>
      <h4 v-if="userParams.id">修改用户</h4>
      <h4 v-else>添加用户</h4>
    </template>
    <template #default>
      <el-form :model="userParams" ref="formRef" :rules="rules">
        <el-form-item label="用户姓名 :" prop="username">
          <el-input
            placeholder="请你输入用户姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称 :" prop="name">
          <el-input
            placeholder="请你输入用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码 :" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请你输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 抽屉--分配角色 -->
  <el-drawer v-model="drawer1" :direction="direction">
    <template #header>
      <h4>分配角色（职位）</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名 ：">
          <input type="text" v-model="userParams.username" :disabled="true" />
        </el-form-item>
        <el-form-item label="职位列表 ：">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="assignRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRolesList"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel1">取消</el-button>
        <el-button type="primary" @click="save1">保存</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import useLayOutSettingStore from '@/store/modules/setting'
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  Records,
  UserResponseData,
  User,
  Roles,
  RolesData,
  RoleVo,
} from '@/api/acl/user/type'
import {
  reqUserInfoAPI,
  reqAddOrUpdateUserAPI,
  reqallRoleAPI,
  requserRolesAPI,
  reqRemoveUserAPI,
  reqSelectUserAPI,
} from '@/api/acl/user/index'
import { ElMessage, ElMessageBox } from 'element-plus'
// 收集添加用户信息
const userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
// 自定义用户名称校验函数
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length > 5) {
    callback()
  } else {
    callback(new Error('用户名称至少要5位！'))
  }
}
// 自定义用户昵称校验函数
const validatorName = (rule: any, value: any, callback: any) => {
  if (value.trim().length > 5) {
    callback()
  } else {
    callback(new Error('用户昵称至少要5位！'))
  }
}
// 自定义用户密码校验函数
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length > 6) {
    callback()
  } else {
    callback(new Error('用户密码至少要5位！'))
  }
}
// 表单校验规则对象
const rules = {
  // 用户名称
  username: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorUsername,
    },
  ],
  // 用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  // 用户密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
let formRef = ref<any>()
// 添加用户抽屉
let drawer = ref<boolean>(false)
let direction = ref<string>('rtl')
// 取消按钮
const cancel = () => {
  drawer.value = false
}
// 保存
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()
  try {
    const res: any = await reqAddOrUpdateUserAPI(userParams)
    if (res.code === 200) {
      // 关闭抽屉
      drawer.value = false
      // 提示消息
      ElMessage({
        type: 'success',
        message: userParams.id ? '更新成功' : '添加成功',
      })
      //获取最新的全部账号的信息--因为有下面的页面刷新，所以下面一行代码可以注释掉，都会回到第一页
      // getHasUser(userParams.id ? pageNo.value : 1)
      // 让浏览器刷新一次，防止改的是当前正在登录的账号，被改后应重新登录
      window.location.reload()
    } else {
      // 关闭抽屉
      drawer.value = false
      // 消息提示
      ElMessage({
        type: 'error',
        message: userParams.id ? '更新失败' : '添加失败',
      })
    }
  } catch (error) {
    throw new Error('添加/更新用户信息异常！')
  }
}
//定义响应式数据:收集用户输入进来的关键字
let keyword = ref<string>('')
// 查询
const search = () => {
  //根据关键字获取相应的用户数据
  getHasUser()
  //清空关键字
  keyword.value = ''
}
//获取模板setting仓库
let settingStore = useLayOutSettingStore()
//重置按钮
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
// table绑定的数据
let userArr = ref<Records>([])
let pageNo = ref<number>(0)
let pageSize = ref<number>(5)
let total = ref<number>(40)
// 当前页码改变
const getHasUser = async (pager = 1) => {
  console.log('🚀 ~ file: index.vue:118 ~ getHasUser ~ pager:', pager)
  pageNo.value = pager
  const res: UserResponseData = await reqUserInfoAPI(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (res.code === 200) {
    userArr.value = res.data.records
    total.value = res.data.total
  }
}
// 当前页条数改变
const handler = (size: number) => {
  console.log('🚀 ~ file: index.vue:129 ~ handler ~ size:', size)
  getHasUser()
}
onMounted(() => {
  getHasUser()
})
// 添加用户
const addUser = () => {
  drawer.value = true
  // 数据对象初始化
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  formRef.value.resetFields()
  //清除上一次的错误的提示信息
  // nextTick(() => {
  //   formRef.value.clearValidate('username')
  //   formRef.value.clearValidate('name')
  //   formRef.value.clearValidate('password')
  // })
}
// table按钮编辑角色
const updateUser = (row: User) => {
  drawer.value = true
  Object.assign(userParams, row)
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 分配角色抽屉
let drawer1 = ref<boolean>(false)
// 多选框选中项绑定值
const checkAll = ref<boolean>(false)
// 全选框的不确定状态，仅负责样式控制
const isIndeterminate = ref<boolean>(true)
const assignRoles = ref<Roles>([])
const allRolesList = ref<Roles>([])
const handleCheckAllChange = (val: boolean) => {
  assignRoles.value = val ? allRolesList.value : []
  //不确定的样式(确定样式)
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  checkAll.value = value.length === allRolesList.value.length
  isIndeterminate.value = value.length !== allRolesList.value.length
}
// table按钮分配角色
const setRole = async (row: User) => {
  drawer1.value = true
  Object.assign(userParams, row)
  const res: RolesData = await reqallRoleAPI(userParams.id as number)
  assignRoles.value = res.data.assignRoles
  allRolesList.value = res.data.allRolesList
}
// 取消按钮
const cancel1 = () => {
  drawer1.value = false
}
// 分配角色确定按钮
const save1 = async () => {
  // 整理参数
  let roleVo: RoleVo = {
    userId: userParams.id as number,
    roleIdList: assignRoles.value.map((item) => {
      return item.id as number
    }),
  }
  //分配用户的职位
  const res = await requserRolesAPI(roleVo)
  if (res.code == 200) {
    //提示信息
    ElMessage({ type: 'success', message: '分配职务成功' })
    //关闭抽屉
    drawer1.value = false
    //获取更新完毕用户的信息,更新完毕留在当前页
    getHasUser(pageNo.value)
  }
}

//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<User[]>([])
// table复选框勾选的时候触发的事件
const selectionChange = (value: any) => {
  selectIdArr.value = value
}

// table按钮删除角色
const deleteUser = async (id: number) => {
  let res = await reqRemoveUserAPI(id)
  if (res.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
//批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  //批量删除的请求
  let result: any = await reqSelectUserAPI(idsList)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
